package traveldream.web.beans;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;

import traveldream.ejb.packetmanagement.PacketMgr;
import traveldream.ejb.packetmanagement.dto.PacketDTO;
import traveldream.ejb.usermanagement.UserMgr;

@ManagedBean(name="prenotazioneBean")
@RequestScoped
public class PrenotazioneBean {

	@ManagedProperty(value="#{personalizeBean.packetToAdd}")
	private PacketDTO personalizedPacket;
	
	@ManagedProperty(value="#{searchPktBean.selectedPacket}")
	private PacketDTO searchedPacket;
	
	private PacketDTO selectedPacket = new PacketDTO();
	
	@EJB
	private UserMgr userMgr;
	@EJB
	private PacketMgr packetMgr;
	
	private List<PacketDTO> listaPrenotazioni = new ArrayList<PacketDTO>();
	
	public PrenotazioneBean(){
	}
	
	public String prenotaPersonalizzato(){
		if(alreadyBookedPers()){
			return("prenotazioneFail.xhtml");
		}
		userMgr.prenotazione(personalizedPacket);
		return("prenotazioneSuccess.xhtml");
	}
	
	public String prenotaRicercato(){
		if(alreadyBookedSearch()){
			return("prenotazioneFail.xhtml");
		}
		userMgr.prenotazione(searchedPacket);
		return("prenotazioneSuccess.xhtml");
	}

	public void getPrenotazioni(){
		List<Long> pidsList = new ArrayList<Long>();
		pidsList = userMgr.ottieniPidsPrenotazioni();
		listaPrenotazioni = searchByPids(pidsList);
	}
	
	private boolean alreadyBookedPers(){
		return userMgr.isBooked(personalizedPacket);
	}
	
	private boolean alreadyBookedSearch(){
		return userMgr.isBooked(searchedPacket);
	}
	public PacketDTO getPersonalizedPacket() {
		return personalizedPacket;
	}

	public void setPersonalizedPacket(PacketDTO personalizedPacket) {
		this.personalizedPacket = personalizedPacket;
	}

	public PacketDTO getSearchedPacket() {
		return searchedPacket;
	}

	public void setSearchedPacket(PacketDTO searchedPacket) {
		this.searchedPacket = searchedPacket;
	}

	public List<PacketDTO> getListaPrenotazioni() {
		return listaPrenotazioni;
	}

	public void setListaPrenotazioni(List<PacketDTO> listaPrenotazioni) {
		this.listaPrenotazioni = listaPrenotazioni;
	}
	
	private List<PacketDTO> searchByPids(List<Long> pids){
		List<PacketDTO> dummyList = new ArrayList<PacketDTO>();
		for(int i=0; i<pids.size(); i++){
			dummyList.add(packetMgr.findByPid(pids.get(i)).get(0));
		}
		return dummyList;
	}

	public PacketDTO getSelectedPacket() {
		return selectedPacket;
	}

	public void setSelectedPacket(PacketDTO selectedPacket) {
		this.selectedPacket = selectedPacket;
	}  
	
	
	
}
